package com.ids.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Set;
import java.util.TreeSet;
import com.ids.bean.UserCreationBean;
import com.ids.util.Constants;
import com.ids.util.DbManager;
import com.ids.util.Utlity;

public class UserCreationDao {
	private static UserCreationDao instance = new UserCreationDao();

	public static UserCreationDao getInstance() {
		return instance;
	}

	public Set<String> createUserAccount(UserCreationBean usercreationBean) {
		Set<String> result = new TreeSet<String>();
		String empCode = usercreationBean.getEmpCode();
		String firstName = usercreationBean.getFirstName();
		String lastName = usercreationBean.getLastName();
		String primaryEmail = usercreationBean.getPrimaryEmail();
		String secondaryEmail = usercreationBean.getSecondaryEmail();
		String designationId = usercreationBean.getDesignationId();
		String reportingTo = usercreationBean.getReportingTo();
		String password = usercreationBean.getPassword();
		String roleId = usercreationBean.getRoleId();
		if (!getEmpCode(empCode)) {
			DbManager dbManager = new DbManager();
			Connection conn = dbManager.getConnection();
			String sqlInsertIntoLogininfo = "insert into logininfo(empCode,password,roleId,noOfAttempts) values(?,?,?,0)";
			String sqlInsertIntoemployees = "insert into employees(empCode, firstname, lastname, primaryemail, secondaryEmail, designationid, reportingto) values(?,?,?,?,?,?,?)";
			try {
				PreparedStatement prepStmt2 = conn
						.prepareStatement(sqlInsertIntoemployees);
				prepStmt2.setString(1, empCode);
				prepStmt2.setString(2, firstName);
				prepStmt2.setString(3, lastName);
				prepStmt2.setString(4, primaryEmail);
				prepStmt2.setString(5, secondaryEmail);
				prepStmt2.setInt(6, Integer.parseInt(designationId));
				prepStmt2.setInt(7, Integer.parseInt(reportingTo));
				prepStmt2.execute();
				result.add(Constants.SUCCESS);
				PreparedStatement prepStmt1 = conn
						.prepareStatement(sqlInsertIntoLogininfo);
				prepStmt1.setString(1, empCode);
				prepStmt1.setString(2, Utlity.MD5(password));
				prepStmt1.setInt(3, Integer.parseInt(roleId));
				prepStmt1.execute();
				result.add(Constants.SUCCESS);
			} catch (Exception e) {
				e.printStackTrace();
				result.add(Constants.FAILURE);
			}
		}
		return result;
	}

	public boolean getEmpCode(String empCode) {
		boolean test = false;
		DbManager dbManager = new DbManager();
		Connection conn = dbManager.getConnection();
		String sqlSelect = "select * from employees where empCode=?";
		try {
			PreparedStatement preStmt = conn.prepareStatement(sqlSelect);
			preStmt.setString(1, empCode);
			ResultSet rs = preStmt.executeQuery();
			if (rs.next()) {
				test = true;
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return test;
	}
}
